<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Products Manager
 * @author	Tran Van Thanh
 * @mail	thanhtran@vietnambiz.com
 * @date	29.08.2011
 */
require_once('admin'.EXT);

class Products extends Admin {

	function __construct()
	{
		parent::__construct();
		$this->load->model(array('products_model', 'user_model'));
		$this->load->helper('upload');
		
		//Get products type
		$this->data['product_type'] = $this->products_model->get_products_type();
		//Get company
		$this->data['company'] 		= $this->products_model->get_company();
		//Get utilities
		$this->data['utilities']	= $this->products_model->get_utilities();		
	}

	function index()
	{
		$page = (isset($_GET['p']) && is_numeric($_GET['p'])) ? $_GET['p'] : 1;

        if(isset($_GET['status'])) {
            $status = ($_GET['status'] == 'active') ? 'yes' : 'no';
            $this->db->where('status', $status);
        }
		if(isset($_GET['company_id']) && $_GET['company_id'] != 0) {    
			$company_id = $_GET['company_id'];        
            $this->db->where('id_company', $company_id);
        }
		if(isset($_GET['protype_id'])) {
            $protype_id = $_GET['protype_id'];
            $this->db->where('id_product_type', $protype_id);
        }
		if(isset($_GET['keyword'])) {    
			$keyword = $_GET['keyword'];
			$keyword = strip_tags($keyword);
			if($keyword == 'keyword')
			{
				$keyword = "";
			}
			else
			{
				$this->db->like('name', $keyword)
            		 ->or_like('code', $keyword)
            		 ->or_like('description', $keyword);
			}
        }

		$this->data['products'] 	= $this->products_model->get_products($page != "" ? $page : 1);
		$this->data['page'] 	= $page;

    	$conf =	array(
    		'base_url'		=> admin_url($this->router->class).'/',
    		'total_rows'	=> $this->products_model->count_all(),
    		'per_page'		=> $this->config->item('products', 'limit'),
    		'cur_page'		=> $page,
    	);
    	$this->pagination->initialize($conf);
    	$this->data['pagnav'] = $this->pagination->display_query_string();

		if($this->input->is_ajax_request()) {
			$this->load->view('products/list', $this->data);
		}
		else {
			$this->data['tpl_file']	= 'products/index';
			$this->load->view('layout/default', $this->data);
		}
	}

	function add()
	{		
		if($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
    		$this->form_validation->set_rules('name', 'Tên sản phẩm', 'required|trim|xss_clean')
    		                      ->set_rules('code', 'Mã sản phẩm', 'trim|xss_clean')
    		                      ->set_rules('cmb_product_type', 'Loại sản phẩm', 'trim|xss_clean')
    		                      ->set_rules('cmb_company', 'Hãng sản phẩm', 'trim|xss_clean')
    		                      ->set_rules('txt_description', 'Mô tả sản phẩm', 'trim|xss_clean');

    		if($this->form_validation->run() == TRUE)
            {
            	if($this->_check_upload()) 
            	{
            		$name 	= $this->input->post('name');
            		
            		$price 	= $this->input->post('txt_price'); 
            		$price	= str_replace(".","",$price);
            		$price	= str_replace(",","",$price);
            		
            		$electric_power	= strip_tags($this->input->post('txt_electric_power'));
            		$electric_power	= str_replace(".","",$electric_power);
            		$electric_power	= str_replace(",","",$electric_power);
            		
            		$cool_power		= strip_tags($this->input->post('txt_cool_power'));
            		$cool_power		= str_replace(".","",$cool_power);
            		$cool_power		= str_replace(",","",$cool_power);
            		
            		$code	= strip_tags($this->input->post('code'));
            		
            		if($this->products_model->check_code_products($code)==FALSE)
                 	{
	            		$data = array(
	            			'name'				=> strip_tags($name),
	            			'name_link'			=> ascii_link($name,'-'),
	            			'code'				=> $code,
	            			'id_company'		=> strip_tags($this->input->post('cmb_company')),
	            			'warranty'			=> strip_tags($this->input->post('txt_warranty')),
	            			'country'			=> strip_tags($this->input->post('txt_country')),
	            			'description'		=> $this->input->post('txt_description'),
	            			'id_product_type'	=> $this->input->post('cmb_product_type'),
	            			'electric_power'	=> $electric_power,
	            			'cool_power '		=> $cool_power,
	            			'size'				=> strip_tags($this->input->post('txt_size')),
	            			'cool_weight'		=> strip_tags($this->input->post('txt_cool_weight')),
	            			'hot_weight'		=> strip_tags($this->input->post('txt_hot_weight')),
	            			'cool_size'			=> strip_tags($this->input->post('txt_cool_size')),
	            			'hot_size'			=> strip_tags($this->input->post('txt_hot_size')),
	            			'power_consumption'	=> strip_tags($this->input->post('txt_power_consumption')),
	            			'absorb_moisture'	=> strip_tags($this->input->post('txt_absorb_moisture')),
	            			'features'			=> $this->input->post('txt_features'),
	            			'price '			=> strip_tags($price),
	            			'price_saleoff '	=> 0,           			
	            			'date_create'		=> date('Y-m-d H:i:s'),
	            		    'hot'				=> $this->input->post('hot'),
	            			'best_sales'		=> $this->input->post('best_sales'),
	            			'dimension'			=> $this->input->post('cmb_dimension'),
	            			'id_utilities'      => $this->input->post('cmb_utilities'),      			        			
	            			'status'			=> $this->input->post('status')
	            		);
	
	            		$product_id = $this->products_model->insert($data);
	
	            		// Upload images
	            		$tt = count($_FILES['images']['name']);            		
	
	            		$album_dir = 'uploads/products/'.$product_id.'/';
	            		create_dir($album_dir);
	
	            		for($i = 0; $i < $tt; $i++) 
	            		{
	            		    $ext = get_ext($_FILES["images"]["name"][$i]);
	                    	if(!in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) {
	                    		continue;
	                    	}
	
	            		    if($_FILES['images']['error'][$i] === 0) {
						        $new_path = $album_dir.$_FILES["images"]["name"][$i];
						        move_uploaded_file($_FILES["images"]['tmp_name'][$i], dirname($_SERVER['SCRIPT_FILENAME']).'/'.$new_path);
	
						        $data = array(
						        	'name'				=> $_FILES["images"]["name"][$i],
						        	'name_link'			=> ascii_link($_FILES["images"]["name"][$i],'-'),					        	
						        	'img_path'			=> $this->_create_thumb($new_path),
						        	'id_product'		=> $product_id,	
						        	'date_create'		=> date('Y-m-d H:i:s'),
						        	'user_create'		=> $_SESSION['_admin']['username'],
						        );
	
						        $this->db->insert('images_products', $data);
	            			}
	            		}
	
	            		die('yes');
                 	}
                 	else
                 	{
                 		die('Mã sản phẩm bị trùng!');
                 	}
            	}
            	else {
            		die('Bạn hãy chọn ảnh sản phẩm để uploads !');
            	}
            }
            else {
            	die(validation_errors());
            }
		}
		
		$this->load->view('products/add', $this->data);
	}

	function edit($product_id = null)
	{
		$product = $this->products_model->get($product_id);
		if(!isset($product->id)) {
			$this->message->add('error', 'Không tìm thấy sản phẩm nào phù hợp !');
			admin_redirect($this->router->class);
		}

		$images = $this->products_model->get_images($product_id);

		if($_SERVER['REQUEST_METHOD'] == 'POST') 
		{
    		$this->form_validation->set_rules('name', 'Tên sản phẩm', 'required|trim|xss_clean')
    		                      ->set_rules('code', 'Mã sản phẩm', 'trim|xss_clean');

    		if($this->form_validation->run() == TRUE)
            {       
            	//Update products
            	$name = $this->input->post('name');
            	
            	$price 	= $this->input->post('txt_price'); 
            	$price	= str_replace(".","",$price);
            	$price	= str_replace(",","",$price);
            	
            	$electric_power	= strip_tags($this->input->post('txt_electric_power'));
            	$electric_power	= str_replace(".","",$electric_power);
            	$electric_power	= str_replace(",","",$electric_power);
            	
            	$cool_power		= strip_tags($this->input->post('txt_cool_power'));
            	$cool_power		= str_replace(".","",$cool_power);
            	$cool_power		= str_replace(",","",$cool_power);
            	
            	$code	= strip_tags($this->input->post('code'));

            	if($this->products_model->check_code_products_edit($product_id,$code)==FALSE)
                {
	            	$arr = array(
	            			'name'				=> strip_tags($name),
	            			'name_link'			=> ascii_link($name,'-'),
	            			'code'				=> $code,
	            			'id_company'		=> strip_tags($this->input->post('cmb_company')),
	            			'warranty'			=> strip_tags($this->input->post('txt_warranty')),
	            			'country'			=> strip_tags($this->input->post('txt_country')),
	            			'description'		=> $this->input->post('txt_description'),
	            			'id_product_type'	=> $this->input->post('cmb_product_type'),
	            			'electric_power'	=> $electric_power,
	            			'cool_power '		=> $cool_power,
	            			'size'				=> strip_tags($this->input->post('txt_size')),
	            			'cool_weight'		=> strip_tags($this->input->post('txt_cool_weight')),
	            			'hot_weight'		=> strip_tags($this->input->post('txt_hot_weight')),
	            			'cool_size'			=> strip_tags($this->input->post('txt_cool_size')),
	            			'hot_size'			=> strip_tags($this->input->post('txt_hot_size')),
	            			'power_consumption'	=> strip_tags($this->input->post('txt_power_consumption')),
	            			'absorb_moisture'	=> strip_tags($this->input->post('txt_absorb_moisture')),
	            			'features'			=> $this->input->post('txt_features'),
	            			'price '			=> strip_tags($price),
	            			'price_saleoff '	=> 0,
	            		    'hot'				=> $this->input->post('hot'),
	            			'best_sales'		=> $this->input->post('best_sales'),
	            			'dimension'			=> $this->input->post('cmb_dimension'),
	            			'id_utilities'      => $this->input->post('cmb_utilities'),      			        			
	            			'status'			=> $this->input->post('status')
	            	);            	
	            	$this->products_model->update($product_id,$arr);
	            	
	            		            	
                	// Upload images            		
                	$album_dir 			= 'uploads/products/'.$product_id.'/';
	            	if(!is_dir($album_dir))
	            	{
	            		create_dir($album_dir);	
	            	}
	            	
	            	$images_id 			= $this->input->post('images_id');                	
                	$images_name 		= $this->input->post('images_name');
                	
                	$tt = count($images_name);
                	
                	for($i = 0; $i < $tt; $i++) 
                	{
                		$data = array(
					        	'name'				=> $_FILES["images"]["name"][$i],
					        	'name_link'			=> ascii_link($_FILES["images"]["name"][$i],'-'),
					        	'id_product'		=> $product_id,            					
					        	'date_create'		=> date('Y-m-d H:i:s'),
					        	'user_create'		=> $_SESSION['_admin']['username'],
				    	);	
				    		
				    	if($_FILES['images']['error'][$i] === 0) 
				    	{
				    		$ext = get_ext($_FILES["images"]["name"][$i]);
				    		if(in_array($ext, array('png', 'gif', 'jpg', 'jpeg'))) 
				    		{
				    			$new_path = $album_dir.$_FILES["images"]["name"][$i];
						        move_uploaded_file($_FILES["images"]['tmp_name'][$i], dirname($_SERVER['SCRIPT_FILENAME']).'/'.$new_path);
						        
						        $data['img_path'] = $this->_create_thumb($new_path);
				    		 	if(isset($images_id[$i])) 
				    		 	{ 
				    		 		// delete old image
					        		if(is_file($images[$i]->img_path)) $this->_delete_image($images[$i]->img_path);
					        	}
				    		}
				    	}
	                	if(isset($images_id[$i])) 
	                	{ 
	                		// update
	            			$this->db->where('id', $images_id[$i])->update('images_products', $data);
	            		}
	            		else if($_FILES['images']['error'][$i] === 0) 
	            		{ 
	            			// insert new
					        $this->db->insert('images_products', $data);
					    }
                	}
	            	die('yes');    
                }
                else
                {
                	die('Mã sản phẩm bị trùng!');
                }        	            	            	
            }
            else {
            	die(validation_errors());
            }
		}

		$this->data['product'] 	= $product;
		$this->data['images'] 	= $images;
		$this->load->view('products/edit', $this->data);
	}

	/**
	 * Delete product
	 * @author Tran Van Thanh
	 * @date 29.08.2011
	 */
    function delete($product_id = null)
    {
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
        	$images = $this->products_model->get_images($product_id);
        	if(count($images) > 0) {
        		foreach($images as $i => $image) {
        			$this->_delete_image($image->img_path);
        		}
        	}

            $this->products_model->delete_product($product_id);

            // Remove dir
            if(is_numeric($product_id)) {
            	$a = array($product_id); $product_id = $a;
            }

            foreach($product_id as $id) {
            	remove_dir('uploads/products/'.$id);
            }

            die('yes');
        }
    }

	function do_action()
	{
		if($_SERVER['REQUEST_METHOD'] == 'POST') {

			$id_list = $this->input->post('id');
			$action = $this->input->post('action');

			if($action == 'delete') {
				$this->delete($id_list);
			}
			elseif($action == 'pending') {
				$this->products_model->update_many($id_list, array('status' => 'no'));
			}
			elseif($action == 'active') {
				$this->products_model->update_many($id_list, array('status' => 'yes'));
			}

			die('yes');
		}
	}

	function change_status()
	{
		$product_id = $this->input->post('product_id');
		$status = $this->input->post('status');

		$this->products_model->update($product_id, array('status' => $status));
		die('yes');
	}
	
	function change_hot()
	{
		$product_id = $this->input->post('product_id');
		$status = $this->input->post('status');

		$this->products_model->update($product_id, array('hot' => $status));
		die('yes');
	}
	
	function change_best_sales()
	{
		$product_id = $this->input->post('product_id');
		$status = $this->input->post('status');

		$this->products_model->update($product_id, array('best_sales' => $status));
		die('yes');
	}

	function load_row($product_id = null)
	{		
		$this->data['products'] = $this->products_model->get($product_id);
		$this->load->view('products/row', $this->data);
	}

	function _check_upload()
	{
		$count = 0;
		if(isset($_FILES['images'])) {
	    	$tt = count($_FILES['images']['name']);
	    	for($i = 0; $i < $tt; $i++) {
	    	    if($_FILES['images']['error'][$i] === 0) $count++;
	    	}
	    }

	    return ($count > 0) ? true : false;
	}

	function _create_thumb($img_path = '')
	{
		$sizes = config_item('thumb_size');
		$this->load->helper('string');
		$pathinfo = pathinfo($img_path);
		$new_name = $pathinfo['basename'];
		
		if($img = $this->db->from('images_products')->where('img_path',$pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name)->get()->row())
		{
			$temp	=	explode('.',$pathinfo['basename']);
			$new_name	=	$temp[0].date('-his-mdy').'.'.$pathinfo['extension'];
		}

		rename($img_path, $pathinfo['dirname'].'/'.$new_name);

        include_once (config_item('phpThumb_dir')."ThumbLib.inc.php");

        $options = array(
		    'resizeUp' 		=> true,
		    'jpegQuality'	=> 88,
        );

		
		foreach($sizes as $size)
		{
			$thumb_dir  = $pathinfo['dirname'].'/thumb_'.$size;
			create_dir($thumb_dir);

			$t_size = explode('-', $size);

		    $thumb 	= PhpThumbFactory::create($pathinfo['dirname'].'/'.$new_name, $options);

		    $thumb->adaptiveResize($t_size[0] + 5, $t_size[1] + 5);
		    $thumb->cropFromCenter($t_size[0], $t_size[1]);
		    $thumb->save($thumb_dir.'/'.$new_name, 'jpg');
		}


		return $pathinfo['dirname'].'/thumb_'.$sizes[0].'/'.$new_name;
	}

	/**
	 * @author 	Nguyen Xuan Hung
	 * @date	07.04.2011
	 */
	function _big_thumb($img_path = '')
	{
		$w = 516;
		$h = 411;

		$filename = str_replace('big_thumb/', '', $img_path);
		$img_path = str_replace('big_thumb/', 'thumb_'.$w.'-'.$h.'/', $img_path);

		$img = getimagesize($filename);
		$o_w = $img[0];
		$o_h = $img[1];

		$ext = get_ext('.', $filename);

		switch($ext) {
		    case 'jpg':
		    case 'jpeg':
		        $old = imagecreatefromjpeg($filename);
		        break;
		    case 'gif':
		        $old = imagecreatefromgif($filename);
		        break;
		    case 'png':
		        $old = imagecreatefrompng($filename);
		        break;
		    default:
		        die('Invalid image type !');
		}

		$new = imagecreatetruecolor($w, $h);
		$white = imagecolorallocate($new, 255, 255, 255);
		imagefill($new, 0, 0, $white);

		if (($o_w / $o_h) >= ($w / $h)) {
		    // by width
		    $nw = $w;
		    $nh = $o_h * ($w / $o_w);
		    $nx = 0;
		    $ny = round(abs($h - $nh) / 2);
		} else {
		    // by height
		    $nw = $o_w * ($h / $o_h);
		    $nh = $h;
		    $nx = round(abs($w - $nw) / 2);
		    $ny = 0;
		}

		imagecopyresized($new, $old, $nx, $ny, 0, 0, $nw, $nh, $o_w, $o_h);

		//header('Content-type: image/jpeg');
		imagejpeg($new, $img_path, 90);
	}

	/**
	 * Delete a image file of products,
	 * @author Tran Van Thanh
	 * @date 29.08.2011
	 */
	function _delete_image($img_path = '')
	{
    	$filename = basename($img_path);
        $sizes = config_item('thumb_size');

    	foreach($sizes as $size) {
    		$path = str_replace($sizes[0], $size, $img_path);
    		if(is_file($path)) unlink($path);
    	}
    	$path = str_replace('/thumb_'.$sizes[0], '', $img_path);
    	if(is_file($path)) unlink($path);
	}	
}

